/**
  ******************************************************************************
  * @file    flash.h
  * @author  Puya Application Team
  * @brief   Header for flash.c module
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2021 Puya Semiconductor.
  * All rights reserved.</center></h2>
  *
  *
  ******************************************************************************
  */

/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __FLASH_H
#define __FLASH_H

/* Includes ------------------------------------------------------------------*/
#include "py32f0xx.h"

#ifdef __cplusplus
extern "C" {
#endif

#define SYSTEM_BASE             (0x1FFF0000UL)
#define BID_BASE                (SYSTEM_BASE + 0x00000BFCUL)
#define OPTION_BASE             (0x1FFF0F80UL)
#define OPTR1_BASE              (OPTION_BASE + 0x00000000UL)
#define OPTR2_BASE              (OPTION_BASE + 0x00000004UL)
#define WRPR_BASE               (OPTION_BASE + 0x00000010UL)
#define PCROP0SR_BASE           (OPTION_BASE + 0x00000014UL)
#define PCROP0ER_BASE           (OPTION_BASE + 0x00000018UL)
#define SECR_BASE               (OPTION_BASE + 0x0000001CUL)
#define DBGMCU_IDCODE           ((DBGMCU->IDCODE) & IDCODE_DEVID_MASK)
#define IDCODE_DEVID_MASK       (0x00000FFFUL)

#define FLASH_OPTR1             (0x1F55E0AA)
#define FLASH_OPTR2             (0xFFFD0002)
#define FLASH_WRPR              (0x0000FFFF)
#define FLASH_PCROP0SR          (0xFE0001FF)
#define FLASH_PCROP0ER          (0xFFFF0000)
#define FLASHSIZE_BASE          (0x1FFFF1160UL)

#define __HAL_FLASH_TIME_REG_SET(__EPPARA0__,__EPPARA1__,__EPPARA2__,__EPPARA3__,__EPPARA4__) \
  do {                                            \
    FLASH->TS0  = (__EPPARA0__)&0xFF;           \
    FLASH->TS1  = ((__EPPARA0__)>>16)&0x1FF;    \
    FLASH->TS3  = ((__EPPARA0__)>>8)&0xFF;      \
    FLASH->TS2P = (__EPPARA1__)&0xFF;           \
    FLASH->TPS3 = ((__EPPARA1__)>>16)&0x7FF;    \
    FLASH->PERTPE = (__EPPARA2__)&0x1FFFF;      \
    FLASH->SMERTPE = (__EPPARA3__)&0x1FFFF;     \
    FLASH->PRGTPE = (__EPPARA4__)&0xFFFF;       \
    FLASH->PRETPE = ((__EPPARA4__)>>16)&0x3FFF; \
  } while(0U)

/* Exported functions ------------------------------------------------------- */
ErrorStatus WriteFlash(uint32_t uiAddr, uint8_t* pubBuf, uint8_t ubLength);
ErrorStatus WriteOption(uint32_t uiAddr, uint8_t* pubBuf, uint8_t ubLength);
ErrorStatus MassErase(void);
ErrorStatus PageErase(uint16_t* puwBuf, uint8_t ubLength, uint8_t ubPageCount);
ErrorStatus SectorErase(uint16_t* puwBuf, uint8_t ubLength);

#ifdef __cplusplus
}
#endif
#endif /* __FLASH_H */

/************************ (C) COPYRIGHT Puya Semiconductor *****END OF FILE****/
